<?php
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author    walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link      http://www.workerman.net/
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 */


namespace Workerman\Protocols;
use Workerman\Connection\TcpConnection;


/**
 * jt808基础分包
 */
class Jt808
{
    /**
     * Check the integrity of the package.
     *
     * @param string        $buffer
     * @return int
     */
    public static function input($buffer,TcpConnection $connection)
    {
        if (strlen($buffer) >= TcpConnection::$maxPackageSize) {
            $connection->close();
            return 0;
        }
        //寻找7e,除开开头的7e,分包
        $buffer=strtolower($buffer);
        $pos = strpos($buffer, "7e",2);
        // No "\n", packet length is unknown, continue to wait for the data so return 0.
        if ($pos === false) {
            return 0;
        }
        // Return the current package length.
        return $pos + 2;
    }

    /**
     * Encode.
     * 替换字节 7d02=>7e 7d01=>7d
     * @param string $buffer
     * @return string
     */
    public static function encode($buffer)
    {
        $buffer=str_replace(pack("H*",'7d02'),pack('H*','7e'),$buffer);
        $buffer=str_replace(pack("H*",'7d01'),pack('H*','7d'),$buffer);
        return substr($buffer,1,-1);
    }

    /**
     * Decode.
     *
     * @param string $buffer
     * @return string
     */
    public static function decode($buffer)
    {
        // Remove "\n"
        return $buffer;
    }
}
